<!-- 装修商品组件：商品卡片 -->
<template>
  <!-- 商品卡片 -->
  <view>
    <!-- 布局1. 单列大图（上图，下内容）-->
   <!-- <view
      v-if="layoutType === LayoutTypeEnum.ONE_COL_BIG_IMG && state.goodsList.length"
      class="goods-sl-box"
    >
      <view
        class="goods-box"
        v-for="item in state.goodsList"
        :key="item.id"
        :style="[{ marginBottom: data.space * 2 + 'rpx' }]"
      >
        <s-goods-column
          class=""
          size="sl"
          :goodsFields="data.fields"
          :tagStyle="data.badge"
          :data="item"
          :titleColor="data.fields.name?.color"
          :subTitleColor="data.fields.introduction.color"
          :topRadius="data.borderRadiusTop"
          :bottomRadius="data.borderRadiusBottom"
          @click="sheep.$router.go('/pages/goods/index', { id: item.id })"
        >
    
          <template v-slot:cart>
            <button class="ss-reset-button cart-btn" :style="[buyStyle]">
              {{ btnBuy.type === 'text' ? btnBuy.text : '' }}
            </button>
          </template>
        </s-goods-column>
      </view>
    </view> -->

    <!-- 布局2. 双列（每一列：上图，下内容）-->
    <view
      v-if="layoutType === LayoutTypeEnum.TWO_COL && state.goodsList.length"
      class="goods-md-wrap ss-flex ss-flex-wrap ss-col-top"
    >
      <view class="goods-list-box">
        <view
          class="left-list"
          :style="[{ paddingRight: data.space + 'rpx', marginBottom: data.space + 'px' }]"
          v-for="(item,index) in state.leftGoodsList"
          :key="item.id"
        >
          <s-goods-column
            class="goods-md-box"
            size="md"	
            :goodsFields="data.fields"
            :tagStyle="data.badge"
            :data="item"
            :titleColor="data.fields.name?.color"
            :subTitleColor="data.fields.introduction.color"
            :topRadius="data.borderRadiusTop"
            :bottomRadius="data.borderRadiusBottom"
            :titleWidth="330 - marginLeft - marginRight"
            @click="sheep.$router.go('/pages/goods/index', { id: item.id })"
            @getHeight="calculateGoodsColumn($event, 'left')"
          >
            <!-- 购买按钮 -->
            <template v-slot:cart>
              <button  v-if="item.skuIds[0].cartCount == 0" class="ss-reset-button cart-btn" :style="[buyStyle]" @click.stop="onleftclickcart(index)">
                {{ btnBuy.type === 'text' ? '购物车' : '' }}
              </button>
			  <view  v-if="item.skuIds[0].cartCount != 0" class="ss-reset-button cart-btn">
			   <su-number-box :min="0"  :max="item.skuIds[0].purchaseMaximum > -1 ? item.skuIds[0].purchaseMaximum : 9999" :step="1" :value='item.skuIds[0].cartCount'
			     @change="onleftNumberChange($event, index)" />
			  				</view>  
            </template>
          </s-goods-column>
        </view>
      </view>
      <view class="goods-list-box">
        <view
          class="right-list"
          :style="[{ paddingLeft: data.space + 'rpx', marginBottom: data.space + 'px' }]"
          v-for="(item,index) in state.rightGoodsList"
          :key="item.id"
        >
          <s-goods-column
            class="goods-md-box"
            size="md"
            :goodsFields="data.fields"
            :tagStyle="data.badge"
            :data="item"
            :titleColor="data.fields.name?.color"
            :subTitleColor="data.fields.introduction.color"
            :topRadius="data.borderRadiusTop"
            :bottomRadius="data.borderRadiusBottom"
            :titleWidth="330 - marginLeft - marginRight"
            @click="sheep.$router.go('/pages/goods/index', { id: item.id })"
            @getHeight="calculateGoodsColumn($event, 'right')"
          >
		  
		  <!-- // @click="sheep.$router.go('/pages/goods/index', { id: item.id })" -->
            <!-- 购买按钮  v-if="!state.showSelect"-->
            <template v-slot:cart>
             <button v-if="item.skuIds[0].cartCount == 0" class="ss-reset-button cart-btn" :style="[buyStyle]" @click.stop="onrightclickcart(index)">
                {{ btnBuy.type === 'text' ? '购物车' : '' }}
              </button>
			 <view  v-if="item.skuIds[0].cartCount != 0" class="ss-reset-button cart-btn">
			  <su-number-box :min="0" :max="item.skuIds[0].purchaseMaximum > -1 ? item.skuIds[0].purchaseMaximum : 9999" :step="1" :value='item.skuIds[0].cartCount'
			    @change="onrightNumberChange($event, index)" />
				</view>  
            </template>
          </s-goods-column>
        </view>
      </view>
    </view>
  <uni-load-more
      v-if="state.pagination.total > 0"
      :status="state.loadStatus"
      :content-text="{
        contentdown: '上拉加载更多',
      }"
      @tap="loadMore"
    />
    <!-- 布局3. 单列小图（左图，右内容） -->
   <!-- <view
      v-if="layoutType === LayoutTypeEnum.ONE_COL_SMALL_IMG && state.goodsList.length"
      class="goods-lg-box"
    >
      <view
        class="goods-box"
        :style="[{ marginBottom: data.space + 'px' }]"
        v-for="item in state.goodsList"
        :key="item.id"
      >
        <s-goods-column
          class="goods-card"
          size="lg"
          :goodsFields="data.fields"
          :data="item"
          :tagStyle="data.badge"
          :titleColor="data.fields.name?.color"
          :subTitleColor="data.fields.introduction.color"
          :topRadius="data.borderRadiusTop"
          :bottomRadius="data.borderRadiusBottom"
          @tap="sheep.$router.go('/pages/goods/index', { id: item.id })"
        >
       
          <template v-slot:cart>
            <button class="ss-reset-button cart-btn" :style="[buyStyle]">
              {{ btnBuy.type === 'text' ? btnBuy.text : '' }}
            </button>
			
          </template>
        </s-goods-column>
      </view>
    </view> -->
  </view>
</template>

<script setup>
  /**
   * 商品卡片
   */
  
  import { computed, reactive, onMounted,watch  } from 'vue';
  import sheep from '@/sheep';
  import SpuApi from '@/sheep/api/product/spu';
   import _ from 'lodash-es';
   import $store from '@/sheep/store';
   import { resetPagination } from '@/sheep/util';
   import { showAuthModal, showShareModal } from '@/sheep/hooks/useModal';
  import {  onLoad,onReachBottom } from '@dcloudio/uni-app';
    import CartApi from '@/sheep/api/trade/cart';
	

   const cart = sheep.$store('cart');
   const prType = sheep.$store('user');
	
	
	
	
	

	
	
	
  // 布局类型
  const LayoutTypeEnum = {
    // 单列大图
    ONE_COL_BIG_IMG: 'oneColBigImg',
    // 双列
    TWO_COL: 'twoCol',
    // 单列小图
    ONE_COL_SMALL_IMG: 'oneColSmallImg',
  };

  const state = reactive({
	  pagination: {
	    list: [],
	    total: 0,
	    pageNo: 1,
	    pageSize: 6,
	  },
    goodsList: [],
	selectedSku:{},
    leftGoodsList: [],
    rightGoodsList: [],
	loadStatus: '',
	showSelect:false
  });
  const props = defineProps({
    data: {
      type: Object,
      default: () => ({}),
    },
    styles: {
      type: Object,
      default: () => ({}),
    },
  });
const userInfo = computed(() => sheep.$store('user').userInfo);
  const { layoutType, btnBuy, spuIds } = props.data || {};
  const { marginLeft, marginRight } = props.styles || {};
  
  

  // 购买按钮样式
  const buyStyle = computed(() => {
    if (btnBuy.type === 'text') {
      // 文字按钮：线性渐变背景颜色
      return {
        background: `linear-gradient(to right, ${btnBuy.bgBeginColor}, ${btnBuy.bgEndColor})`,
      };
    }
    if (btnBuy.type === 'img') {
      // 图片按钮
      return {
        width: '54rpx',
        height: '54rpx',
        background: `url(${sheep.$url.cdn(btnBuy.imgUrl)}) no-repeat`,
        backgroundSize: '100% 100%',
      };
    }
  });
  
 
 async function onleftclickcart (e){
  	 
  	  
  	 // 页面登录拦截
  	 if (!$store('user').isLogin) {
  	 	  // console.log("denglMode")
  	   showAuthModal();
  	   return;
  	 }
	 
	 
	 
	 
	 const { data, code } = await CartApi.addCart({
	   skuId: state.leftGoodsList[e].skuIds[0].skuId,
	   count: state.leftGoodsList[e].skuIds[0].purchaseMinimum,
	 });
	 // 刷新购物车列表
	 if (code === 0) {
	 		
	 	 state.leftGoodsList[e].skuIds[0].cartCount = data
	 		
	     sheep.$store('cart').getList();	
	 }
  	 // state.leftGoodsList[e].skuIds[0].cartCount =  1
  	 //  var ge = {  		  
  		//   goods_num: 1,
  		//   id: state.leftGoodsList[e].skuIds[0].skuId,	  
  		  
  	 //   }
  	 //  sheep.$store('cart').add(ge);
   	 
   };
  
 
  async function onleftNumberChange(e,index){
  	  
  	  
  	  if (e === state.leftGoodsList[index].skuIds[0].purchaseMinimum-1) {
  	    		       
  	   
  	   const { data, code } = await CartApi.deleteByCart({
  	     skuId:state.leftGoodsList[index].skuIds[0].skuId,
  	   
  	   });
	   
	   
	   
	   
	   
	   
	   

  	   // 刷新购物车列表
  	   if (code === 0) {
  	   		
  	   		 state.leftGoodsList[index].skuIds[0].cartCount =  0
  	   		
  	         sheep.$store('cart').getList();	
  	   }
  	   
  	  }else{
		  
		  console.log(state.leftGoodsList[index].skuIds[0].skuId)
		  	  
		  var ge = {	    
		     goods_num: e,
		     id: state.leftGoodsList[index].skuIds[0].skuId,	  	    		  
		  }
		  sheep.$store('cart').add(ge);
		  
	  }
  	   	  
  };
   
 async function onrightclickcart (e){
	  	    
  	 // 页面登录拦截
  	 if (!$store('user').isLogin) {
  	 	  // console.log("denglMode")
  	   showAuthModal();
  	   return;
  	 }
	 
	 	
	 const { data, code } = await CartApi.addCart({
	   skuId: state.rightGoodsList[e].skuIds[0].skuId,
	   count: state.rightGoodsList[e].skuIds[0].purchaseMinimum,
	 });
	 // 刷新购物车列表
	 if (code === 0) {
	 		
	 	 state.rightGoodsList[e].skuIds[0].cartCount = data
	 		
	     sheep.$store('cart').getList();	
	 }
	  
   	 
   };
  
  async function onrightNumberChange(e,index){
	  
	  
	  
	    console.log(e)
	  if (e === state.rightGoodsList[index].skuIds[0].purchaseMinimum-1) {
	    		       
	   
	   const { data, code } = await CartApi.deleteByCart({
	     skuId:state.rightGoodsList[index].skuIds[0].skuId,
	   
	   });
	   
	   console.log(data)
	   // 刷新购物车列表
	   if (code === 0) {
	   		
	   		 state.rightGoodsList[index].skuIds[0].cartCount =  0
	   		
	         sheep.$store('cart').getList();	
	   }
	   
	    	
	   
	   	return;
	  }else{
	  		  
	  		  
	  		  var ge = {
	  		    
	  		     goods_num: e,
	  		     id: state.rightGoodsList[index].skuIds[0].skuId,	  
	  		    		  
	  		  }
			    console.log(state.rightGoodsList[index].skuIds[0].skuId)
	  		  sheep.$store('cart').add(ge);
	  		  
	  }
	    
	  
  };
 // 输入框改变数量
 //  function onNumberChange(e) {
 
	//   console.log('ddfef',e)
 //    if (e === 0) {
		
	// 	console.log('ddfef',e)
	// 	 state.showSelect = !state.showSelect
	// 	 return;
	// }
 //    if (state.selectedSku.goods_num === e) return;
 //         state.selectedSku.goods_num = e;
 //  };
  
  // 清空列表
  function emptyList() {
    resetPagination(state.pagination);
    state.leftGoodsList = [];
    state.rightGoodsList = [];
	state.goodsList = [];
    count = 0;
    leftHeight = 0;
    rightHeight = 0;
  }
  //region 商品瀑布流布局
  // 下一个要处理的商品索引
  let count = 0;
  // 左列的高度
  let leftHeight = 0;
  // 右列的高度
  let rightHeight = 0;

  /**
   * 计算商品在左列还是右列
   * @param height 商品的高度
   * @param where 添加到哪一列
   */
  function calculateGoodsColumn(height = 0, where = 'left') {
    // 处理完
    if (!state.goodsList[count]) return;
    // 增加列的高度
    if (where === 'left') leftHeight += height;
    if (where === 'right') rightHeight += height;
    // 添加到矮的一列
	
    if (leftHeight <= rightHeight) {
      state.leftGoodsList.push(state.goodsList[count]);
    } else {
      state.rightGoodsList.push(state.goodsList[count]);
    }
    // 计数
    count++;
  }
  
  

  /**
   * 根据商品编号列表，获取商品列表
   * @param ids 商品编号列表
   * @return {Promise<undefined>} 商品列表
   */
  async function getGoodsListByIds(ids) {
  
	 state.loadStatus = 'loading';
	 const { code, data } = await SpuApi.getSpuPage({
	   pageNo: state.pagination.pageNo,
	   pageSize: state.pagination.pageSize, 
	   userId:userInfo.value.id
	 });
	 if (code !== 0) {
	   return;
	 }
	 console.log(data)
	 state.goodsList = _.concat(state.goodsList, data.list);
	 state.pagination.total = data.total;
	 state.loadStatus = state.goodsList.length < state.pagination.total ? 'more' : 'noMore';
	  calculateGoodsColumn();
   
  }
  
  watch(() => cart.list, (newValue, oldValue) => {
    
   
	oldValue.forEach((items, indexne) => {
	      
			state.rightGoodsList.forEach((item, index) => {
			         
			   		   if(items.sku.id === item.skuIds[0].skuId){
						   				   
						    state.rightGoodsList[index].skuIds[0].cartCount =  0
					   }				  
			   		   
			   });
			   
			   
	});
	
	oldValue.forEach((items, indexne) => {
	      
			state.leftGoodsList.forEach((item, index) => {
			         
			   		   if(items.sku.id === item.skuIds[0].skuId){					   				   
						    state.leftGoodsList[index].skuIds[0].cartCount =  0
					   }
			   		   
			   		   
			   });
			   
			   
	});
	
	
	
	
	 newValue.forEach((items, indexne) => {
	       
		state.rightGoodsList.forEach((item, index) => {
		         
		   		   if(items.sku.id === item.skuIds[0].skuId){
					   				   
					    state.rightGoodsList[index].skuIds[0].cartCount =  items.count
				   }
		   		   
		   });
		   
		   
	 });
	 
	 newValue.forEach((items, indexne) => {
	       
	 		state.leftGoodsList.forEach((item, index) => {
	 		         
	 		   		   if(items.sku.id === item.skuIds[0].skuId){
	 					   				   
	 					    state.leftGoodsList[index].skuIds[0].cartCount =  items.count
	 				   }
	 		   		   
	 		   		   
	 		   });
	 		   
	 		   
	 });
	  
	 // state.rightGoodsList[index].skuIds[0].cartCount =  0
	// return
	 // getGoodsListByIds();
  });
  
  
  
  watch(() => prType.procurementType, (newValue, oldValue) => {
    
	console.log(newValue)
	 emptyList()
    getGoodsListByIds();
  	 // state.rightGoodsList[index].skuIds[0].cartCount =  0
  	// return
  	 // getGoodsListByIds();
  });
  
  // 加载更多
  function loadMore() {
	  
    if (state.loadStatus === 'noMore') {
      return;
    }
    state.pagination.pageNo++;
     getGoodsListByIds();
  };
  
 // 上拉加载更多
  onReachBottom(() => {
	  
    loadMore();
  });
   
   onLoad(() => {
	  
	  
	   // showAuthModal();
	  console.log("dfdfe")
	  
   });
  
  // 初始化
  onMounted(async () => {
	    console.log('mounted');
		
	// var dict  =	uni.getStorageSync('userInfo');
	  // console.log(userInfo);
	 // console.log(uni.getStorageSync('user-store').userInfo.id);
	  // console.log(userInfo.value.id);
	   getGoodsListByIds();
    // if (layoutType === LayoutTypeEnum.TWO_COL) {
    //   // 分列
    //   calculateGoodsColumn();
    // }
  });
</script>

<style lang="scss" scoped>
  .goods-md-wrap {
    width: 100%;
	// height: 100rpx;
  }

  .goods-list-box {
    width: 50%;
    box-sizing: border-box;

    .left-list {
      &:nth-last-child(1) {
        margin-bottom: 0 !important;
      }
    }

    .right-list {
      &:nth-last-child(1) {
        margin-bottom: 0 !important;
      }
    }
  }

  .goods-box {
    &:nth-last-of-type(1) {
      margin-bottom: 0 !important;
    }
  }

  .goods-md-box,
  .goods-sl-box,
  .goods-lg-box {
    position: relative;

    .cart-btn {
      position: absolute;
      bottom: 18rpx;
      right: 20rpx;
      z-index: 11;
      height: 50rpx;
      line-height: 50rpx;
      padding: 0 20rpx;
      border-radius: 25rpx;
      font-size: 24rpx;
      color: #fff;
    }
  }
</style>
